<script setup lang="ts">
import dayjs from 'dayjs'
import type { InfoGridItem } from './ProjectTable.vue'
import { fetchProjectNodeListAPI } from '@/apis/fetchProjectNodeList'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

const props = defineProps<{
  project: Project
}>()

defineEmits([
  'callContact',
  'uploadPayment',
  'initialAfterSales',
  'assignTeammates',
  'updateProjectNode',
  'viewPaymentRecord',
  'updateUserInfo',
])

const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

const activeNodes = ref<ProjectNode[]>([])
const allNodes = computed(() => {
  return projectConfigStore.nodeLists[props.project.project_type_id!]
})

onMounted(async () => {
  const res = await fetchProjectNodeListAPI({
    project_id: props.project.id!.toString()!,
  }, userInfoStore.userInfo!.token!)
  if (res.data?.code === 1)
    activeNodes.value = res.data?.data || []
  else uni.showToast({ title: res.data?.msg, icon: 'none' })
})

function getTableInfo(project: Project): InfoGridItem[] {
  if (userInfoStore.belongTo(['0'])) {
    return [
      { label: '业务员', value: project.salesman_name || '未知' },
      { label: '项目总额', value: `¥${project.money_total}`, color: '#FF2636' },
      { label: '装修类型', value: project.project_type_name || '未知' },
      { label: '工期截止', value: project.duration ? dayjs.unix(Number(project.duration)).format('YYYY.MM.DD') : '未知' },
      { label: '装修面积', value: `${project.extent}` },
    ]
  }
  else if (userInfoStore.belongTo(['4'])) {
    return [
      { label: '业务员', value: project.salesman_name || '未知' },
      { label: '项目总额', value: `¥${project.money_total}`, color: '#FF2636' },
      { label: '装修类型', value: project.project_type_name || '未知' },
      { label: '工期截止', value: project.duration ? dayjs.unix(Number(project.duration)).format('YYYY.MM.DD') : '未知' },
      { label: '装修面积', value: `${project.extent}` },
      { label: '业主', value: project.contacts_name || '未知', showTag: true },
    ]
  }
  else {
    return [
      { label: '业务员', value: project.salesman_name || '未知' },
      { label: '项目总额', value: `¥${project.money_total}`, color: '#FF2636' },
      { label: '装修类型', value: project.project_type_name || '未知' },
      { label: '工期截止', value: project.duration ? dayjs.unix(Number(project.duration)).format('YYYY.MM.DD') : '未知' },
      { label: '装修面积', value: `${project.extent}` },
      { label: '项目节点', value: project.node_name || '未知', color: '#FE6F15' },
    ]
  }
}

const isShowWarning = computed(() => {
  const isWillOutofdate = Number(props.project.duration) - dayjs(Date.now()).unix() < 864000
  const neededShow = props.project.status?.toString() !== '3'
  return isWillOutofdate && neededShow
})
</script>

<template>
  <view class="flex flex-col bg-white rounded-20rpx">
    <!-- 卡片 Header START -->
    <view
      class="relative flex flex-col pt-20rpx pr-157rpx pb-20rpx pl-30rpx"
    >
      <view class="flex items-center">
        <view class="text-28rpx leading-48rpx text-secondary">
          {{ project.name ? project.name : '未知项目' }}
        </view>
        <Spacer width="4" />
        <image
          v-if="isShowWarning"
          class="flex-shrink-0 w-52rpx h-40rpx"
          src="@/static/images/warning.png"
        />
      </view>
      <view
        v-if="userInfoStore.belongTo(['4'])"
        class="self-start mt-4rpx px-16rpx py-8rpx text-28rpx leading-28rpx text-brand bg-#FFEEE2 rounded-full"
      >
        当前节点：{{ project.node_name || '未开始' }}
      </view>
      <view
        class="absolute top-0 right-0 px-20rpx py-9rpx text-white text-28rpx leading-28rpx bg-brand rounded-tr-20rpx rounded-bl-12rpx"
        :style="{ backgroundColor: '#FF6D0A' }"
      >
        {{ projectConfigStore.projectStatusStr[project.status!] || '未知' }}
      </view>
    </view>
    <!-- 卡片 Header END -->
    <!-- 如果是工长，（2024.04.07新增），或者如果是工人，（2024.04.30新增），显示缩略版本 -->
    <block v-if="userInfoStore.belongTo(['2']) || userInfoStore.userInfo!.group_id! >= 5">
      <view class="flex items-center justify-between ml-32rpx mr-18rpx mb-30rpx">
        <view
          class="self-start mt-4rpx px-16rpx py-8rpx text-28rpx leading-28rpx text-brand bg-#FFEEE2 rounded-full"
        >
          {{ project.node_name || '未开始' }}
        </view>
        <view class="flex items-center text-28rpx font-medium">
          <view class="text-#999999">
            工期截止：
          </view>
          <view class="text-#333333">
            {{ project.duration ? dayjs.unix(Number(project.duration)).format('YYYY.MM.DD') : '未知' }}
          </view>
        </view>
      </view>
    </block>
    <!-- 常规显示 -->
    <block v-else>
      <Divider />
      <view class="p-30rpx">
        <ProjectTable :info="getTableInfo(project)" />
      </view>
      <view class="px-30rpx">
        <ProjectNodes
          :active-nodes="activeNodes"
          :nodes="allNodes"
        />
      </view>
      <Spacer height="36" />
      <Divider />
      <!-- 卡片 Footer START -->
      <view class="flex flex-row-reverse justify-between items-center p-30rpx max-w-690rpx">
        <view v-if="userInfoStore.belongTo(['4'])" class="flex">
          <RGButton size="medium" corner="small" type="secondary" @tap.stop="$emit('updateProjectNode')">
            修改节点
          </RGButton>
          <Spacer width="18" />
          <RGButton size="medium" auto-width corner="small" type="secondary" @tap.stop="$emit('updateUserInfo')">
            编辑
          </RGButton>
          <Spacer width="18" />
          <RGButton v-if="project.status?.toString() === '2'" size="medium" corner="small" type="primary" @tap.stop="$emit('uploadPayment')">
            上传打款信息
          </RGButton>
          <RGButton v-if="project.status?.toString() === '3'" size="medium" corner="small" type="primary" @tap.stop="$emit('initialAfterSales')">
            发起售后
          </RGButton>
        </view>
        <view v-else-if="userInfoStore.belongTo(['2'])" class="flex">
          <RGButton size="medium" corner="small" type="secondary" @tap.stop="$emit('assignTeammates', { identity: '工长' })">
            设置团队人员
          </RGButton>
          <Spacer width="18" />
          <RGButton v-if="project.status?.toString() === '2'" size="medium" corner="small" type="primary" @tap.stop="$emit('updateProjectNode')">
            修改项目节点
          </RGButton>
          <RGButton v-if="project.status?.toString() === '3'" size="medium" corner="small" type="primary" @tap.stop="$emit('initialAfterSales')">
            发起售后
          </RGButton>
        </view>
        <view v-else-if="userInfoStore.belongTo(['1'])" class="flex">
          <RGButton size="medium" corner="small" type="primary" @tap.stop="$emit('assignTeammates', { identity: '地区经理' })">
            设置团队人员
          </RGButton>
        </view>
        <view v-else-if="userInfoStore.belongTo(['3'])" class="flex">
          <RGButton size="medium" corner="small" type="primary" @tap.stop="$emit('viewPaymentRecord')">
            查看打款信息
          </RGButton>
        </view>
        <view v-if="userInfoStore.belongTo(['3', '2', '1'])" class="flex items-center w-full">
          <view class="flex-shrink-1 max-w-90rpx overflow-hidden text-ellipsis text-30rpx leading-30rpx text-secondary font-bold">
            {{ project.contacts_name || '未知' }}
          </view>
          <view class="flex-shrink-0 ml-10rpx px-22rpx py-5rpx text-24rpx leading-24rpx text-white bg-brand rounded-full">
            业主
          </view>
        </view>
      </view>
    <!-- 卡片 Footer END -->
    </block>
  </view>
</template>
